#!/usr/bin/env bash

set -eu
script_name=$0
DB_BACKEND=$(echo "${script_name}" | cut -d- -f2)
export DB_BACKEND

die() {
    echo >&2 "$@"
    exit 1
}

PGHOST=${PGHOST:-127.0.0.1}
PGPORT=${PGPORT:-5432}
PGPASSWORD=${PGPASSWORD:-postgres}
PGUSER=${PGUSER:-postgres}
export PGHOST
export PGPORT
export PGPASSWORD
export PGUSER

about() {
    die "usage: ${script_name} [ config_yaml | setup | dump <backup_file> | restore <backup_file> ]"
}

check_requirements() {
    if ! command -v psql >/dev/null; then
        die "missing required program 'psql' as a postgres client (package postgressql-client on debian like system)"
    fi
    if ! command -v pg_dump >/dev/null; then
        die "missing required program 'pg_dump' (package postgresql-client on debian like system)"
    fi
    if ! command -v pg_restore >/dev/null; then
        die "missing required program 'pg_restore' (package postgresql-client on debian like system)"
    fi
}

exec_sql() {
    cmd="${1?Missing required sql command}"
    psql <<< "${cmd}"
}

setup() {
    exec_sql "DROP DATABASE IF EXISTS crowdsec_test;"
    exec_sql "DROP USER IF EXISTS crowdsec_test;"
    exec_sql "CREATE USER crowdsec_test WITH ENCRYPTED PASSWORD 'crowdsec_test';"
    exec_sql "CREATE DATABASE crowdsec_test OWNER crowdsec_test;"
}

dump() {
    backup_file="${1?Missing file to backup database to}"
    pg_dump -Ft --dbname crowdsec_test --clean --create --file "${backup_file}"
}

restore() {
    backup_file="${1?missing file to restore database from}"
    [[ -f "${backup_file}" ]] || die "Backup file ${backup_file} doesn't exist"
    pg_restore --dbname crowdsec_test --clean "${backup_file}"
}

config_yaml() {
    yq e '
        .db_config.type=strenv(DB_BACKEND)|
        .db_config.user="crowdsec_test" |
        .db_config.password="crowdsec_test" |
        .db_config.db_name="crowdsec_test"  |
        .db_config.host=strenv(PGHOST) |
        .db_config.port=env(PGPORT) |
        .db_config.sslmode="disable" |
        del(.db_config.db_path)
    ' -i "${CONFIG_YAML}"
}

[[ $# -lt 1 ]] && about

check_requirements

case "$1" in
    setup)
        setup
        ;;
    config-yaml)
        config_yaml
        ;;
    dump)
        shift
        dump "$@"
        ;;
    restore)
        shift
        restore "$@"
        ;;
    exec_sql)
        PGDATABASE=${PGDATABASE:-crowdsec_test}
        export PGDATABASE
        shift
        exec_sql "$@"
        ;;
    *)
        about
        ;;
esac;
